// 由生产者驱动

#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <time.h>

#include "../include/thread.h"
#include "../include/mutex.h"
#include "../include/condvar.h"

using namespace mix;

std::string buffer;
Mutex bufferLock;
CondVar cond( bufferLock);

void thread1_run() {
    Thread::sleep( 1000);
    for ( int i = 0; i < 10;) {

        bufferLock.lock();
        if ( buffer.empty()) {
            buffer = "car.";
            printf( "product a %s\n", buffer.c_str());
            bufferLock.unlock();
            cond.signal();
            ++i;
        }
        else  
            bufferLock.unlock();

        Thread::sleep( rand() % 500);
    }
}


void thread2_run() {
    for ( int i = 0; i < 10; ++i) {

        bufferLock.lock();
        while ( buffer.empty()) {
            cond.wait();
        }

        printf( "buy a %s\n", buffer.c_str());
        buffer.clear();
        bufferLock.unlock();
    }

}


int main() {
    Thread t1( thread1_run);
    Thread t2( thread2_run);

    t1.start();
    t2.start();

    t1.join();
    t2.join();

    return 0;
}
